/**
 * @Author: Wang chunsheng  email:2192138785@qq.com
 * @Date:   2021-10-30 10:40:37
 * @Last Modified by:   Wang chunsheng  email:2192138785@qq.com
 * @Last Modified time: 2024-11-26 20:09:15
 */
import router from './router'
import store from '@projectName/store'
import Cookies from 'js-cookie'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {
  getToken,
  isWeChatBrowser
} from '@projectName/utils/auth' // get token from cookie
import {
  config
} from '@projectName/utils/publicUtil'
import getPageTitle from '@projectName/utils/get-page-title'
import {
  getsignup
} from '@projectName/api/user.js'
import {
  getAuthUrl
} from './views/diandi_subscription/wxmp/api/wx-account-fans'
NProgress.configure({
  showSpinner: false
}) // NProgress Configuration

const whiteList = ['/login', '/register', '/forget', '/qcord'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()
  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()
  store.dispatch('app/setConfig', config)
  console.log('hasToken00', hasToken)

  if (hasToken) {
    console.log('hasToken1', hasToken)
    await store.dispatch('elForm/changeSite', config.siteUrl, config.bmapAk)
    if (to.path.indexOf('login') !== -1) {
      next({
        path: '/dashboard'
      })
    } else {
      try {
        const permission_routes = store.getters.permission_routes &&
          store.getters.permission_routes.length > 0 &&
          store.getters.LeftMenu.length > 0
        if (Cookies.get('is_roles') && permission_routes) {
          console.log('hasToken00-is_roles', hasToken)

          const {
            user
          } = await store.dispatch('user/getInfo', window.location.host)
          if (!user.mobile && to.path !== '/profile/bind') {
            /**
             * 用户资料校验强制拦截
             */
            next({
              path: '/profile/bind'
            })
          } else {
            next()
          }
        } else {
          console.log('hasToken00-un-is_roles', hasToken)

          const {
            roles
          } = await store.dispatch('user/getInfo', window.location.host)
          await store.dispatch('user/setRoles', roles)
          const accessRoutes = await store.dispatch('permission/getMenus')
          router.addRoutes(accessRoutes)
          next({
            ...to,
            replace: true
          })
        }
      } catch (error) {
        console.log('error-login', error)
        await store.dispatch('user/resetToken')
        next(`/login?redirect=${to.path}`)
        console.log('error', error)
      }
    }
  } else {
    if (isWeChatBrowser()) {
      const code = to.query.code
      try {
        if (code) {
          const response = await getsignup({
            code
          })
          console.log('根据code获取用户信息', response)
          if (response && response.code === 200) {
            store.dispatch('user/set_token', response.data.access_token)
            const {
              roles
            } = response.data
            await store.dispatch('user/setRoles', roles)
            const accessRoutes = await store.dispatch('permission/getMenus')
            router.addRoutes(accessRoutes)
            if (response.data.user.mobile) {
              next({
                path: '/dashboard'
              })
            } else {
              next({
                path: '/profile/bind'
              })
            }
          } else {
            next(`/login?redirect=${to.path}`)
          }
        } else {
          const fullUrl = window.location.href
          const response = await getAuthUrl({
            redirect_url: encodeURI(
              fullUrl
            )
          })
          if (response && response.code === 200) {
            // eslint-disable-next-line require-atomic-updates
            window.location.href = response.data.url
          } else {
            next(`/login?redirect=${to.path}`)
          }
        }
      } catch (error) {
        console.log('微信浏览器错误 error', error)
      }
    } else {
      if (whiteList.indexOf(to.path) !== -1) {
        next()
      } else {
        next(`/login?redirect=${to.path}`)
      }
    }
  }
  // Ensure progress bar is done in all cases
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
